package study.threadpackage;

/**
 * Created by 小生
 * 2019/2/25 15:29.
 * https://www.cnblogs.com/cynchanpin/p/6746844.html
 */
public class Thread1 extends Thread{
    private String name;
    public Thread1(String name) {
        this.name = name;
    }

    public void run() {
        /*时间的运用*/
        /*for(int i = 0; i < 5; i++) {
            System.out.println(name + "执行" + i);
            try {
                //线程睡眠是为了不让第一个线程独霸该进程所获取的CPU资源
                sleep(1);
            }catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }*/
        /*join 相当于前端的回调*/
        System.out.println(Thread.currentThread().getName() + " 线程开始执行!");
        for (int i = 0; i < 5; i++) {
            System.out.println("子线程" + name + "执行 : " + i);
            try {
                sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(Thread.currentThread().getName() + " 线程执行结束!");
    }

    public static void main(String[] args) {
        /*time运用*/
        /*Thread1 thread1 = new Thread1("A");
        Thread1 thread2 = new Thread1("B");
        thread1.start();
        thread2.start();*/

        /*join运用*/
        //不加join
        /*System.out.println(Thread.currentThread().getName()+"主线程执行開始!");
        Thread1 mTh1=new Thread1("A");
        Thread1 mTh2=new Thread1("B");
        mTh1.start();
        mTh2.start();
        System.out.println(Thread.currentThread().getName()+ "主线程执行结束!");*/

        //加join 总结：不用join主线程最先执行完  用了join的线程会再main方法之前执行 类似前端js的回调
        System.out.println(Thread.currentThread().getName()+"主线程执行開始!");
        Thread1 mTh1=new Thread1("A");
        Thread1 mTh2=new Thread1("B");
        mTh1.start();
        mTh2.start();
        try {
            mTh1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            mTh2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+ "主线程执行结束!");
    }
}
